import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:tender_flutter/generated/json/base/json_convert_content.dart';
import 'package:tender_flutter/page/home/model/city_entity.dart';
import 'package:tender_flutter/page/home/model/user_info_entity.dart';
import 'package:tender_flutter/utils/utils.dart';

class SPUtils {
  /// 内部构造方法，可避免外部暴露构造函数，进行实例化
  SPUtils._internal();

  static SharedPreferences _spf;

  static Future<SharedPreferences> init() async {
    if (_spf == null) {
      _spf = await SharedPreferences.getInstance();
    }
    return _spf;
  }

  static Future<bool> clean() async {
    return _spf.clear();
  }

  static Future<bool> remove(String key) {
    return _spf.remove(key);
  }

  ///是否第一次安装
  static Future<bool> saveInstallFlag(bool isInstall) {
    return _spf.setBool('isInstall', isInstall);
  }

  static bool getInstallFlag() {
    return _spf.getBool('isInstall') ?? true;
  }

  ///用户信息
  static Future<bool> saveUserInfo(UserInfoEntity userInfo) {
    var jsonString = jsonEncode(userInfo);
    return _spf.setString('key_userinfo', jsonString);
  }

  static UserInfoEntity getUserInfo() {
    String value = _spf.getString('key_userinfo');

    if (!isEmpty(value)) {
      UserInfoEntity userInfoEntity =
          JsonConvert.fromJsonAsT<UserInfoEntity>(jsonDecode(value));
      return userInfoEntity;
    } else {
      return UserInfoEntity();
    }
  }

  static Future<bool> removeUserInfo() {
    return _spf.remove("key_userinfo");
  }

  /// 用户位置信息
  static Future<bool> saveAddres(CityEntity city) {
    var jsonString = jsonEncode(city);
    return _spf.setString('key_address', jsonString);
  }

  static CityEntity getCity() {
    String value = _spf.getString('key_address');

    if (!isEmpty(value)) {
      CityEntity city = JsonConvert.fromJsonAsT<CityEntity>(jsonDecode(value));
      return city;
    } else {
      return null;
    }
  }

  static Future<bool> removeCity() {
    return _spf.remove("key_address");
  }

  ///Token
  static Future<bool> saveToken(String token) {
    return _spf.setString('key_token', token);
  }

  static String getToken() {
    return _spf.getString('key_token');
  }

  static Future<bool> removeToke() {
    return _spf.remove("key_token");
  }

  ///是否已登陆
  static bool isLogined() {
    String value = _spf.getString('key_userinfo');
    return isEmpty(value) ? false : true;
  }
}
